package com.lalala.Dao;

import com.lalala.entity.Student;
import com.lalala.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 *持久层<p>将信息储存到数据库中
 *
 * @author lalala
 * @createdate 2021/9/1 20:30 周三
 */
public class ManageDAO {
	static QueryRunner Runner = new QueryRunner(JDBCUtils.getDataSource());

	/**
	 * 添加学生信息
	 * @param stu 学生
	 * @return 成功条数
	 */
	public int add(Student stu) {
		try {
			return Runner.update("insert into information values(?,?,?,?,?)", stu.toParam());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 删除学生信息
	 * @param stuID 学生
	 * @return 成功条数
	 */
	public int delByID(String stuID) {
		try {
			return Runner.update("delete from information where studentID = ?", stuID);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 修改学生信息
	 * @param student 学生对象
	 * @return 成功条数
	 */
	public int alter(Student student) {
		try {
			return Runner.update(
					"update information " +
							"set name = ?,gender = ?,birthday = ?,phoneNumber = ?" +
							"where studentID = ?",
					student.getName(),student.getGender(), student.getBirthday(),
					student.getPhoneNumber(), student.getStudentID());
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		return 0;
	}

	/**
	 * 根据学号从数据库中读取学生对象
	 * @param stuID 学号
	 * @return 学生对象
	 */
	public Student getStudent(String stuID){
		try {
			return Runner.query("select * from information where studentID = ?",
					new BeanHandler<>(Student.class),stuID);
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询学生信息（ID）
	 * @param stuID 学号
	 * @return 储存信息的map对象
	 */
	public Map<String, Object> queryInformationByID(String stuID){
		try {
			return Runner.query("select * from information where studentID = ?", new MapHandler(), stuID);
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询全部学生信息
	 * @return 储存学生信息(map)的List
	 */
	public List<Map<String,Object>> queryInformationAll() {
		try {
			return Runner.query("select * from information",new MapListHandler());
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		return null;
	}
}
